﻿using CommonLib.CodeEntity;
using CommonLib.Info;
using CommonLib.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace CommonLib.Base;

public abstract class SqlFilesRead
{
    public void Read(IList<string> list, Assembly assembly)
    {
        if (string.IsNullOrEmpty(ConstUtil.InPath) || !Directory.Exists(ConstUtil.InPath)) return;
        SqlFactory.Init(assembly);
        var sqlfiles = Directory.GetFiles(ConstUtil.InPath, "*.sql", SearchOption.AllDirectories);
        foreach (var file in sqlfiles)
        {
            if(!file.Contains("ASGNKNMCNG1")) continue;
            Console.WriteLine(file);
            var code = FileCode.GetCode(file);
            var Lines = File.ReadAllLines(file, code).Select(s => s.Trim())
                .Where(s => !string.IsNullOrEmpty(s) && !s.Equals("/"))
                .Select(s => s.ReplaceSpace().ToUpper().Trim()).ToList();
            Lines = SqlStringList.Init(Lines);
            var root = ExecuteLexer(FormatLines(Lines));
            root.Enhance();
            var sub = root.SqlList();
            if (sub.Count > 0)
            {
                File.WriteAllLines(Path.Combine(ConstUtil.OutPath, Path.GetFileName(file)), sub);
            }
        }
    }

    protected abstract List<string> FormatLines(List<string> Lines);

    protected abstract RootCodeEntity ExecuteLexer(List<string> Lines);
}
